__author__ = 'chen_ju0606@163.com'

import shutil

import os

from docx import Document
from docx.enum.text import WD_BREAK_TYPE, WD_BREAK
from docx.opc.oxml import parse_xml
from docx.oxml.ns import qn, nsdecls
from docx.shared import Inches, Pt, RGBColor
import pandas as pd

from config.readconfig import ini
from tools.logger import log


def extract_case_code_from_excel(excel_path, column=3, row=2):
    try:
        # 读取Excel文件，从第二行开始读取
        df = pd.read_excel(excel_path, header=None)

        # 选择C列，即第三列（列索引为2），并从第二行开始读取
        c_column_values = df.iloc[row-1:, column-1]  # iloc[1:]表示从第二行开始，索引为2的列即C列

        # 去除空白行
        c_column_values = c_column_values.dropna()

        # 转换为列表并返回
        return c_column_values.tolist()
    except Exception:
        log.error(f'请检查文件{excel_path}')
        return []

def classify_images_by_title(image_dir, titles):
    titles_images = {title: [] for title in titles}
    for filename in os.listdir(image_dir):
        if filename.endswith('.png') or filename.endswith('.jpg'):
            for title in titles:
                if title == filename[11:-8]:
                    titles_images[title].append(os.path.join(image_dir, filename))
    return titles_images


def create_docx_with_titles_and_images(titles_images, output_path):
    case_code_from = int(ini.case_code_from) or 3
    if case_code_from in [1, 2, 3]:

        doc = Document()

        # doc.add_paragraph('analise-mode=case-code')
        for title, images in titles_images.items():
            # 添加标题
            heading = doc.add_heading(level=1)
            run = heading.add_run(title)

            # 设置字体为 +中文正文
            run.font.name = '黑体'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')

            # 设置字号为二号
            run.font.size = Pt(22)  # 二号对应22磅字体

            # 设置加粗
            run.bold = True

            # 强制应用字体样式 (通过 rFonts 的 ASCII 和 HighAnsi 属性)
            run._element.rPr.rFonts.set(qn('w:ascii'), 'Times New Roman')  # 或其他你需要的字体
            run._element.rPr.rFonts.set(qn('w:hAnsi'), 'Times New Roman')  # 或其他你需要的字体

            # 添加对应图片
            for image_path in images:
                # doc.add_paragraph()  # 添加空行，避免图片紧贴标题
                doc.add_picture(image_path, width=Inches(5.5))  # 设置图片宽度

        # 保存新文档
        doc.save(output_path)
    elif case_code_from == 4:
        try:
            doc = Document('input.docx')
            images_list = []
            for paragraph in doc.paragraphs:
                if paragraph.style.name.startswith('Heading') and '_' in paragraph.text:
                    heading = paragraph.text[paragraph.text.rfind('_')+1:]
                    images_list = titles_images.get(heading)
                if paragraph.text.startswith('测试截图') and paragraph.style.name == 'Normal':

                    for image_path in images_list:
                        paragraph.add_run().add_picture(image_path, width=Inches(5.5))
                    images_list = []
            doc.save(output_path)
        except:
            log.error(f'生成报告异常: titles_images map: {titles_images}')
            raise ValueError(f'生成报告异常')


def extract_docx_headings(docx_path):
    try:
        doc = Document(docx_path)
        headings = []

        for paragraph in doc.paragraphs:
            # Check the paragraph style to determine if it's a heading
            if paragraph.style.name.startswith('Heading'):
                headings.append(paragraph.text)

        return headings
    except Exception:
        log.error(f'请检查文件{docx_path}')
        return []

def extract_case_code_list(file_path):
    case_code_from = int(ini.case_code_from) or 3
    if case_code_from == 1:
        log.info(f'使用证迹导入模板(code模式, 即只有案例编号模板)作为输入文件docx')
        return extract_docx_headings(f'{file_path}.docx')
    elif case_code_from == 2:
        log.info(f'使用旧案例模板作为输入文件xlsx')
        return extract_case_code_from_excel(f'{file_path}.xlsx', 1, 2)
    elif case_code_from == 3:
        log.info(f'使用新案例模板作为输入文件xlsx')
        return extract_case_code_from_excel(f'{file_path}.xlsx', 3, 2)
    elif case_code_from == 4:
        log.info(f'使用证迹导入模板(id模式, 即平台导出模板)作为输入文件docx')
        return extract_docx_headings_by_id(f'{file_path}.docx')
    else:
        log.error(f'配置文件中红配置项CASE_CODE_FROM错误，应该为1，2，3，实际为{case_code_from}')
        return []


def back_up_images(src_dir, tar_dir):
    # 确保目标目录存在，如果不存在则创建
    if not os.path.exists(tar_dir):
        os.makedirs(tar_dir)

    # 遍历源目录下的所有文件
    for file_name in os.listdir(src_dir):
        # 构建完整的文件路径
        src_file = os.path.join(src_dir, file_name)
        dest_file = os.path.join(tar_dir, file_name)

        # 移动文件到目标目录
        shutil.move(src_file, dest_file)

def extract_docx_headings_by_id(docx_path):
    try:
        doc = Document(docx_path)
        headings = []
        for paragraph in doc.paragraphs:
            if paragraph.style.name.startswith('Heading') and '_' in paragraph.text:
                # print(f'{paragraph.text} | {paragraph.text[paragraph.text.rfind("_") + 1:]}')
                headings.append(paragraph.text[paragraph.text.rfind('_') + 1:])
        return headings
    except Exception:
        log.error(f'请检查文件{docx_path}')
        return []


if __name__ == '__main__':

    pass
